/* Copyright Statement:
 *
 * This software/firmware and related documentation ("MediaTek Software") are
 * protected under relevant copyright laws. The information contained herein is
 * confidential and proprietary to MediaTek Inc. and/or its licensors. Without
 * the prior written permission of MediaTek inc. and/or its licensors, any
 * reproduction, modification, use or disclosure of MediaTek Software, and
 * information contained herein, in whole or in part, shall be strictly
 * prohibited.
 *
 * MediaTek Inc. (C) 2014. All rights reserved.
 *
 * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
 * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
 * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
 * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
 * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
 * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
 * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
 * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
 * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
 * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
 * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
 * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
 * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
 * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
 * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
 * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
 * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
 *
 * The following software/firmware and/or related documentation ("MediaTek
 * Software") have been modified by MediaTek Inc. All revisions are subject to
 * any receiver's applicable license agreements with MediaTek Inc.
 */

package com.android.camera.manager;

import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.android.camera.CameraActivity;
import com.android.camera.Log;
import com.android.camera.ModeChecker;
import com.android.camera.R;
import com.android.camera.Util;
import com.android.camera.animation.AnimationFadeIn;
import com.android.camera.animation.AnimationFadeOut;
import com.android.camera.animation.AnimationListener;
import com.android.camera.ui.PickerButton;
import com.android.camera.ui.PickerButton.Listener;

import com.mediatek.camera.setting.preference.IconListPreference;
import com.mediatek.camera.setting.preference.ListPreference;
import com.mediatek.camera.setting.SettingConstants;

//bug_id:DWYQLSQ-288 add by wzf power below 15% close flashlight satrt
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.content.Context;
import android.provider.Settings;
import android.util.TypedValue;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
//bug_id:DWYQLSQ-288 add by wzf power below 15% close flashlight end

public class PickerManager extends ViewManager implements Listener,
        CameraActivity.OnPreferenceReadyListener, CameraActivity.OnParametersReadyListener {
    private static final String TAG = "PickerManager";

    public interface PickerListener {
        boolean onSlowMotionPicked(String turnon);

        boolean onHdrPicked(String value);

        boolean onSelfTimerPicked(String value);

        boolean onGesturePicked(String value);

        boolean onCameraPicked(int camerId);

        boolean onFlashPicked(String flashMode);

        boolean onStereoPicked(boolean stereoType);

        boolean onModePicked(int mode, String value, ListPreference preference);

        // for RGK new UI solution by anxiang.xiao 20160506
        // for control panel menu switch
        boolean onSettingsPicked(String value);

        boolean onLomoEffectPicked();

        boolean onScenePicked(String scene);

        void onSceneListShowing(boolean show);
    }

    private static final int DELAY_FOR_HIDE_SCENELIST = 200;
    private static final int MAX_NUM_OF_SHOWEN = 3;

    private View mPickerTop;
    private FrameLayout mOptions;
    private ListView mSceneList;
    private PickerButton mSettings;
    private PickerButton mSlowMotion;
    private PickerButton mGestureShot;
    private PickerButton mHdrPicker;
    private PickerButton mSelfTimerPicker;
    private PickerButton mFlashPicker;
    private PickerButton mCameraPicker;
    private PickerButton mStereoPicker;
    private PickerButton mLomoEffect;
    private PickerButton mScenePicker;
    private View mSceneListLayout;

    private boolean mDefineOrder = true;
    private boolean mIsLomoEffectShown = false;
    private boolean mIsSceneShown = false;
    private boolean mPreferenceReady;
    private boolean mNeedEnabledLater;
    private int mButtonClicked = -1;
    private Animation mFadeIn;
    private Animation mFadeOut;
    private CameraActivity mContext;
    private Handler mHandler = new Handler();
    private PickerListener mListener;
    private SceneListAdapter mSceneApater;
    private CharSequence[] mCurrentEntries = null;

    private static final int PICKER_BUTTON_NUM = 10;
    private static final int BUTTON_HDR = 1;
    private static final int BUTTON_FLASH = 2;
    private static final int BUTTON_CAMERA = 3;
    private static final int BUTTON_STEREO = 4;
    private static final int BUTTON_SLOW_MOTION = 5;
    private static final int BUTTON_GESTURE_SHOT = 6;
    // for control panel menu switch
    private static final int BUTTON_SETTINGS = 0;
    private static final int BUTTON_LOMO_EFFECT = 7;
    private static final int BUTTON_SCENE = 8;
    private static final int BUTTON_SELFTIMER = 9;
    private PickerButton[] mPickerButtons = new PickerButton[PICKER_BUTTON_NUM];

    private int[] mButtonPriority = {
            BUTTON_SETTINGS, BUTTON_SCENE, BUTTON_HDR, BUTTON_SELFTIMER, BUTTON_FLASH,
            BUTTON_CAMERA, BUTTON_LOMO_EFFECT, BUTTON_SLOW_MOTION, BUTTON_STEREO,
            BUTTON_GESTURE_SHOT
    };
    private static boolean[] sShownStatusRecorder = new boolean[PICKER_BUTTON_NUM];
    static {
        // for control panel menu switch
        sShownStatusRecorder[BUTTON_SETTINGS] = false;
        sShownStatusRecorder[BUTTON_SLOW_MOTION] = true;
        sShownStatusRecorder[BUTTON_HDR] = false;
        sShownStatusRecorder[BUTTON_FLASH] = false;
        sShownStatusRecorder[BUTTON_CAMERA] = false;
        sShownStatusRecorder[BUTTON_STEREO] = true;
        sShownStatusRecorder[BUTTON_GESTURE_SHOT] = true;
        sShownStatusRecorder[BUTTON_LOMO_EFFECT] = false;
        sShownStatusRecorder[BUTTON_SCENE] = true;
        sShownStatusRecorder[BUTTON_SELFTIMER] = false;
    }

    private Runnable mHideSceneList = new Runnable() {

        @Override
        public void run() {
            hideSceneList();
        }
    };

    private View.OnClickListener mOptionClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    };

    private android.view.animation.Animation.AnimationListener mSceneListFadeOutListener 
            = new android.view.animation.Animation.AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            if (mListener != null) {
                mListener.onSceneListShowing(false);
            }
        }
    };

    public PickerManager(CameraActivity context) {
        super(context, VIEW_LAYER_PICKER);
        mContext = context;
        context.addOnPreferenceReadyListener(this);
        context.addOnParametersReadyListener(this);
    }

    @Override
    protected View getView() {
        View view = inflate(R.layout.onscreen_pickers);
        setFileter(false);

        mPickerTop = view.findViewById(R.id.onscreen_picker_top);
        mSlowMotion = (PickerButton) view.findViewById(R.id.onscreen_slow_motion_picker);
        mGestureShot = (PickerButton) view.findViewById(R.id.onscreen_gesture_shot_picker);
        mHdrPicker = (PickerButton) view.findViewById(R.id.onscreen_hdr_picker);
        mSelfTimerPicker = (PickerButton) view.findViewById(R.id.onscreen_selftimer_picker);
        mFlashPicker = (PickerButton) view.findViewById(R.id.onscreen_flash_picker);
        mCameraPicker = (PickerButton) view.findViewById(R.id.onscreen_camera_picker);
        mStereoPicker = (PickerButton) view.findViewById(R.id.onscreen_stereo3d_picker);
        mLomoEffect = (PickerButton) view.findViewById(R.id.onscreen_lomo_effect);
        // for control panel menu switch
        mSettings = (PickerButton) view.findViewById(R.id.onscreen_settings_picker);
        mScenePicker = (PickerButton) view.findViewById(R.id.onscreen_scene_picker);
        mPickerButtons[BUTTON_SETTINGS] = mSettings;
        mPickerButtons[BUTTON_SLOW_MOTION] = mSlowMotion;
        mPickerButtons[BUTTON_GESTURE_SHOT] = mGestureShot;
        mPickerButtons[BUTTON_HDR] = mHdrPicker;
        mPickerButtons[BUTTON_FLASH] = mFlashPicker;
        mPickerButtons[BUTTON_CAMERA] = mCameraPicker;
        mPickerButtons[BUTTON_STEREO] = mStereoPicker;
        mPickerButtons[BUTTON_LOMO_EFFECT] = mLomoEffect;
        mPickerButtons[BUTTON_SCENE] = mScenePicker;
        mPickerButtons[BUTTON_SELFTIMER] = mSelfTimerPicker;
        mSlowMotion.setVisibility(View.GONE);
        applyListeners();
        mOptions = (FrameLayout) view.findViewById(R.id.options);
        mSceneListLayout = view.findViewById(R.id.scene_list_layout);
        mSceneList = (ListView) view.findViewById(R.id.scene_list);
        View sceneBack = view.findViewById(R.id.scene_back);
        sceneBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                hideSceneList();
            }
        });
        return view;
    }

    private void applyListeners() {
        for (PickerButton button : mPickerButtons) {
            button.setListener(this);
        }
        mLomoEffect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (canBePicked(mLomoEffect, null)) {
                    mIsLomoEffectShown = !mIsLomoEffectShown;
                    mListener.onLomoEffectPicked();
                }
            }
        });
    }

    public void setListener(PickerListener listener) {
        mListener = listener;
    }

    @Override
    public void onPreferenceReady() {
        Log.i(TAG, "onPreferenceReady()");
        mPreferenceReady = true;
    }

    @Override
    public void onOrientationChanged(int orientation) {
        super.onOrientationChanged(orientation);
        Util.setOrientation(mSceneListLayout, orientation, true);
    }

    @Override
    public void onCameraParameterReady() {
        Log.i(TAG, "onCameraParameterReady(), mDefineOrder:" + mDefineOrder + "" +
                ", mPreferenceReady:" + mPreferenceReady);
        if (!mPreferenceReady) {
            return;
        }

        // the max number of button shown on PickerManager UI is 4, Slow motion,
        // hdr, flash, dual camera,
        // stereo camera have high priority, gesture, smile have low priority,
        // but gesture's priority is
        // higher than smile, if the order of button is definite, do not
        // redefine again.
        if (!mDefineOrder) {
            int count = 0;
            for (int i = 0; i < mButtonPriority.length; i++) {
                ListPreference pref = null;
                boolean visible = false;
                int buttonIndex = mButtonPriority[i];
                switch (buttonIndex) {
                    case BUTTON_SLOW_MOTION:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_SLOW_MOTION);
                        break;
                    case BUTTON_HDR:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_HDR);
                        break;
                    case BUTTON_SELFTIMER:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_SELF_TIMER);
                        break;
                    case BUTTON_FLASH:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_FLASH);
                        break;
                    case BUTTON_CAMERA:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_DUAL_CAMERA);
                        visible = ModeChecker.getCameraPickerVisible(getContext());
                        if (visible) {
                            count++;
                            if (pref != null) {
                                pref.showInSetting(false);
                            }
                        }
                        pref = null;
                        break;
                    case BUTTON_STEREO:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_STEREO_MODE);
                        visible = ModeChecker.getStereoPickerVisibile(getContext());
                        if (visible) {
                            count++;
                            if (pref != null) {
                                pref.showInSetting(false);
                            }

                        }
                        pref = null;
                        break;
                    case BUTTON_GESTURE_SHOT:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_GESTURE_SHOT);
                        break;
                    case BUTTON_SETTINGS:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_CONTROL_PANEL);
                        break;
                    case BUTTON_LOMO_EFFECT:
                        break;
                    default:
                        break;
                }

                if (pref != null && pref.getEntries() != null
                        && pref.getEntries().length > 1) {
                    pref.showInSetting(false);
                    count++;
                    if (BUTTON_GESTURE_SHOT == buttonIndex) {
                        sShownStatusRecorder[BUTTON_GESTURE_SHOT] = false;
                    }
                }

                Log.i(TAG, "count:" + count + ", buttonIndex:" + buttonIndex);
                if (count >= MAX_NUM_OF_SHOWEN) {
                    break;
                }
            }
            mDefineOrder = true;
        } else {
            for (int i = 0; i < mButtonPriority.length; i++) {
                ListPreference pref = null;
                int buttonIndex = mButtonPriority[i];
                switch (buttonIndex) {
                    case BUTTON_SLOW_MOTION:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_SLOW_MOTION);
                        break;
                    case BUTTON_HDR:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_HDR);
                        break;
                    case BUTTON_SELFTIMER:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_SELF_TIMER);
                        break;
                    case BUTTON_FLASH:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_FLASH);
                        break;
                    case BUTTON_CAMERA:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_DUAL_CAMERA);
                        break;
                    case BUTTON_STEREO:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_STEREO_MODE);
                        break;
                    case BUTTON_GESTURE_SHOT:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_GESTURE_SHOT);
                        break;
                    // for control panel menu switch
                    case BUTTON_SETTINGS:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_CONTROL_PANEL);
                        break;
                    case BUTTON_SCENE:
                        pref = (IconListPreference) getContext()
                                .getListPreference(SettingConstants.ROW_SETTING_SCENCE_MODE);
                        break;
                    default:
                        break;
                }
                if (pref != null) {
                    pref.showInSetting(sShownStatusRecorder[buttonIndex]);
                }
            }
        }

        refresh();
    }

    private void refreshVisibility() {
        ListPreference hdrPref = (IconListPreference) getContext()
                .getListPreference(SettingConstants.ROW_SETTING_HDR);
        ListPreference selfTimerPref = (IconListPreference) getContext()
                .getListPreference(SettingConstants.ROW_SETTING_SELF_TIMER);

        if (mContext.getBottomModePicker().getModeIndex() == RGK_BottomModePicker.MODE_PHOTO_INDEX
                && mContext.isFrontCamera()) {
            if (hdrPref != null) {
                hdrPref.showInSetting(true);
            }
            if (selfTimerPref != null) {
                selfTimerPref.showInSetting(false);
            }
        } else {
            if (hdrPref != null) {
                hdrPref.showInSetting(false);
            }
            if (selfTimerPref != null) {
                selfTimerPref.showInSetting(true);
            }
        }

        ListPreference cameraPref = (IconListPreference) getContext()
                .getListPreference(SettingConstants.ROW_SETTING_DUAL_CAMERA);
        if (cameraPref != null) {
            if (mContext.getBottomModePicker()
                    .getModeIndex() == RGK_BottomModePicker.MODE_SLOWMOTION_INDEX) {
                cameraPref.setEnabled(false);
            } else {
                cameraPref.setEnabled(true);
            }
        }
    }

    @Override
    public void hide() {
        hideSceneList();
        hideOptions();
        if (mContext.getCurrentMode() == ModePicker.MODE_VIDEO
                && "on".equals(mContext.getISettingCtrl().getSettingValue(
                        SettingConstants.KEY_HDR))) {
            for (int i = PICKER_BUTTON_NUM - 1; i >= 0; i--) {
                if (mPickerButtons[i] == mHdrPicker) {
                    mPickerButtons[i].setEnabled(true);
                    mPickerButtons[i].setClickable(false);
                    mPickerButtons[i].setVisibility(View.VISIBLE);
                    super.fadeIn();
                } else {
                    Util.fadeOut(mPickerButtons[i]);
                }
            }
        } else {
            super.hide();
        }
    }

    @Override
    public boolean canBePicked(PickerButton button, ListPreference preference) {
        boolean canBePicked = false;
        if (mContext != null) {
            canBePicked = !mContext.isModeSwitching();
        }
        return canBePicked;
    }

    @Override
    public boolean onPicked(PickerButton button, ListPreference pref, String newValue) {
        boolean picked = false;
        String key = pref.getKey();
        if (mListener != null) {
            int index = -1;
            for (int i = 0; i < PICKER_BUTTON_NUM; i++) {
                if (button.equals(mPickerButtons[i])) {
                    index = i;
                    break;
                }
            }

            switch (index) {
                case BUTTON_FLASH:
                case BUTTON_HDR:
                case BUTTON_SELFTIMER:
                    onButtonClicked(pref, index);
                    mButtonClicked = index;
                    picked = true;
                    break;
                case BUTTON_SLOW_MOTION:
                    picked = mListener.onSlowMotionPicked(newValue);
                    break;
                case BUTTON_GESTURE_SHOT:
                    button.setValue(newValue);
                    picked = mListener.onGesturePicked(newValue);
                    break;
                case BUTTON_CAMERA:
                    picked = mListener.onCameraPicked(Integer.parseInt(newValue));
                    break;
                case BUTTON_STEREO:
                    picked = mListener.onStereoPicked("1".endsWith(newValue) ? true : false);
                    break;
                // for control panel menu switch
                case BUTTON_SETTINGS:
                    button.setValue(newValue);
                    picked = mListener.onSettingsPicked(newValue);
                    break;
                case BUTTON_SCENE:
                    onSceneClicked(pref);
                    picked = true;
                    break;
                default:
                    break;
            }

        }
        Log.i(TAG, "onPicked(" + key + ", " + newValue + ") mListener=" + mListener + " return "
                + picked);
        return picked;
    }

    public void setCameraId(int cameraId) {
        if (mCameraPicker != null) {
            mCameraPicker.setValue("" + cameraId);
        }
    }

    @Override
    public void onRefresh() {
        Log.d(TAG, "onRefresh(), mPreferenceReady:" + mPreferenceReady);
        if (!mPreferenceReady) {
            return;
        }

        if (mContext.getBottomModePicker().isSwitchToSlowMotionPending()) {
            return;
        }

        if (mNeedEnabledLater) {
            setEnabled(true);
            mNeedEnabledLater = false;
        }

        refreshVisibility();
        mSlowMotion.initialize((IconListPreference) getContext().getListPreference(
                SettingConstants.ROW_SETTING_SLOW_MOTION));
        mGestureShot.initialize((IconListPreference) getContext().getListPreference(
                SettingConstants.ROW_SETTING_GESTURE_SHOT));
        mHdrPicker.initialize((IconListPreference) getContext().getListPreference(
                SettingConstants.ROW_SETTING_HDR));
        mSelfTimerPicker.initialize((IconListPreference) getContext().getListPreference(
                SettingConstants.ROW_SETTING_SELF_TIMER));
        mFlashPicker.initialize((IconListPreference) getContext().getListPreference(
                SettingConstants.ROW_SETTING_FLASH));
        mCameraPicker.initialize((IconListPreference) getContext().getListPreference(
                SettingConstants.ROW_SETTING_DUAL_CAMERA));
        mStereoPicker.initialize((IconListPreference) getContext().getListPreference(
                SettingConstants.ROW_SETTING_STEREO_MODE));
        // for control panel menu switch
        mSettings.initialize((IconListPreference) getContext().getListPreference(
                SettingConstants.ROW_SETTING_CONTROL_PANEL));
        mScenePicker.initialize((IconListPreference) getContext().getListPreference(
                SettingConstants.ROW_SETTING_SCENCE_MODE));

        // mSlowMotion.refresh();
        mGestureShot.refresh();
        mHdrPicker.refresh();
        mSelfTimerPicker.refresh();
        // bug_id:DWYQLSQ-288 add by wzf power below 15% close flashlight end
        if (CameraActivity.getBatteryLevel() <= 15) {
            mFlashPicker.setImageResource(R.drawable.btn_flash_off);
        } else {
            mFlashPicker.refresh();
        }
        // bug_id:DWYQLSQ-288 add by wzf power below 15% close flashlight end

        boolean isCameraPickerVisible = ModeChecker.getCameraPickerVisible(getContext());
        if (isCameraPickerVisible) {
            mCameraPicker.refresh();
        } else {
            mCameraPicker.setVisibility(View.GONE);
        }
        boolean isStereoPickerVisibile = ModeChecker.getStereoPickerVisibile(getContext());
        if (isStereoPickerVisibile) {
            mStereoPicker.refresh();
        } else {
            mStereoPicker.setVisibility(View.GONE);
        }
        // for control panel menu switch
        if (mSettings != null) {
            mSettings.setImageResource(R.drawable.btn_settings);
            mSettings.refresh2();
        }
        mScenePicker.refresh();
        if (isSceneListShowing() && mSceneApater != null) {
            mSceneApater.notifyDataSetChanged();
        }
        refreshOptionValues();
//        hideSceneList();
//        hideOptions();
    }

    @Override
    protected void onRelease() {
        super.onRelease();
    }

    @Override
    public void setEnabled(boolean enabled) {
        // FengYibin, avoid pickers' flicker.
        if (mContext.getBottomModePicker().isSwitchToSlowMotionPending() && enabled) {
            mNeedEnabledLater = true;
            return;
        }

        super.setEnabled(enabled);
        for (PickerButton button : mPickerButtons) {
            if (button != null) {
                if (button == mFlashPicker && CameraActivity.getBatteryLevel() <= 15) {
                    mFlashPicker.enableFilter(true);
                    mFlashPicker.setEnabled(false);
                    mFlashPicker.setClickable(false);
                } else {
                    button.setEnabled(enabled);
                    button.setClickable(enabled);
                }
            }
        }
    }

    /**
     * Force to enable the picker button indicated by the input key.
     * 
     * @param key The key used to indicate the picker button.
     */
    public void forceEnable(String key) {
        if (SettingConstants.KEY_HDR.equals(key)) {
            mHdrPicker.forceEnable();
        }
    }

    /**
     * Do not to force enable the picker button indicated by the input key.
     * 
     * @param key The key used to indicate the picker button.
     */
    public void cancelForcedEnable(String key) {
        if (SettingConstants.KEY_HDR.equals(key)) {
            mHdrPicker.cancelForcedEnable();
        }
    }

    public void cameraButtonClick() {
        mCameraPicker.onClick(mCameraPicker);
    }

    public void showLomoEffectIndicator() {
        if (mLomoEffect != null) {
            mLomoEffect.setVisibility(View.VISIBLE);
        }
    }

    public void hideLomoEffectIndicator() {
        if (mLomoEffect != null) {
            mLomoEffect.setVisibility(View.GONE);
        }
    }

    public boolean onBackPressed() {
        return hideSceneList() || hideOptions();
    }

    @Override
    public boolean collapse(boolean force) {
        return hideSceneList() || hideOptions();
    }

    public void setLomoEffectIndicatorEnabled(boolean enabled) {
        if (mLomoEffect != null) {
            mLomoEffect.setEnabled(enabled);
        }
    }

    public boolean isScenePickerVisible() {
        return (mScenePicker != null && mScenePicker.getVisibility() == View.VISIBLE);
    }

    private boolean isSceneListShowing() {
        return (mSceneListLayout != null && mSceneListLayout.getVisibility() == View.VISIBLE);
    }

    private boolean isOptionsShowing() {
        return (mOptions != null && mOptions.getVisibility() == View.VISIBLE);
    }

    private void showOptionValues(final ListPreference pref, final int index, boolean isRefresh) {
        mContext.getCameraAppUI().dismissInfo();
        CharSequence[] entries = pref.getEntries();
        if (isRefresh) {
            PickerButton picker = null;
            switch (index) {
                case BUTTON_FLASH:
                    picker = mFlashPicker;
                    break;
                case BUTTON_HDR:
                    picker = mHdrPicker;
                    break;
                case BUTTON_SELFTIMER:
                    picker = mSelfTimerPicker;
                    break;
                default:
                    break;
            }
            if (picker != null) {
                if (picker.getVisibility() != View.VISIBLE) {
                    hideOptions();
                    return;
                }
            }
            if (mCurrentEntries == null) {
                hideOptions();
                return;
            }
            if (mCurrentEntries.equals(entries)) {
                return;
            }
        }
        mCurrentEntries = entries;
        if (entries.length <= 1) {
            if (isOptionsShowing()) {
                hideOptions();
            }
            return;
        }
        CharSequence[] entryValues = pref.getEntryValues();
        final String currentEntryValue = pref.getValue();
        RelativeLayout pre;
        RelativeLayout now;
        LinearLayout nowOptions;
        int currentOptionIndex = 0;
        now = new RelativeLayout(getContext());
        now.setBackgroundResource(R.color.preview_top_background);
        nowOptions = new LinearLayout(getContext());
        nowOptions.setOrientation(LinearLayout.HORIZONTAL);
        nowOptions.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams optionsLLParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        for (int i = 0; i < entries.length; i++) {
            TextView text = new TextView(getContext());
            text.setText(entries[i].toString());
            text.setTextColor(getContext().getResources().getColorStateList(R.color.text_colorful));
            text.setTextSize(TypedValue.COMPLEX_UNIT_PX, getContext().getResources()
                    .getDimensionPixelOffset(R.dimen.picker_options_text_size));
            text.setGravity(Gravity.CENTER);
            text.setFocusable(false);
            int padding = getContext().getResources()
                    .getDimensionPixelSize(R.dimen.picker_options_text_padding);
            text.setPadding(padding, 0, padding, 0);
            final String entryValue = entryValues[i].toString();
            if (currentEntryValue.equals(entryValue)) {
                text.setSelected(true);
                currentOptionIndex = i;
            }

            text.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (!currentEntryValue.equals(entryValue)) {
                        switch (index) {
                            case BUTTON_FLASH:
                                mListener.onFlashPicked(entryValue);
                                break;
                            case BUTTON_HDR:
                                mListener.onHdrPicked(entryValue);
                                break;
                            case BUTTON_SELFTIMER:
                                mListener.onSelfTimerPicked(entryValue);
                                break;
                            default:
                                break;
                        }
                        pref.setValue(entryValue);
                    }
                    hideOptions();
                }
            });
            nowOptions.addView(text, i, optionsLLParams);
        }
        ImageView icon = new ImageView(getContext());
        icon.setScaleType(ScaleType.FIT_CENTER);
        icon.setImageResource(pref.getIconId(currentOptionIndex));
        RelativeLayout.LayoutParams optionsRLParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        optionsRLParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        RelativeLayout.LayoutParams optionIconRLParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        optionIconRLParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        optionIconRLParams.leftMargin = getContext().getResources()
                .getDimensionPixelSize(R.dimen.onscreen_picker_margin);
        now.addView(nowOptions, optionsRLParams);
        now.addView(icon, optionIconRLParams);
        if (isOptionsShowing()) {
            pre = (RelativeLayout) mOptions.getChildAt(0);
            now.setVisibility(View.INVISIBLE);
            mOptions.addView(now);
            new AnimationFadeOut(pre).setListener(new AnimationListener() {

                @Override
                public void onAnimationStart(com.android.camera.animation.Animation animation) {

                }

                @Override
                public void onAnimationEnd(com.android.camera.animation.Animation animation) {
                    mOptions.removeViewAt(0);
                }
            }).animate();
            new AnimationFadeIn(now).animate();
        } else {
            mOptions.removeAllViews();
            mOptions.addView(now);
            new AnimationFadeIn(mOptions).animate();
            new AnimationFadeOut(mPickerTop).animate();
        }
    }

    private void onButtonClicked(final ListPreference pref, final int index) {
        if (isOptionsShowing() && mButtonClicked == index) {
            hideOptions();
        } else {
            showOptionValues(pref, index, false);
        }
    }

    private void refreshOptionValues() {
        if (!isOptionsShowing()) {
            return;
        }
        ListPreference pref = null;
        switch (mButtonClicked) {
            case BUTTON_HDR:
                pref = (IconListPreference) getContext()
                        .getListPreference(SettingConstants.ROW_SETTING_HDR);
                break;
            case BUTTON_SELFTIMER:
                pref = (IconListPreference) getContext()
                        .getListPreference(SettingConstants.ROW_SETTING_SELF_TIMER);
                break;
            case BUTTON_FLASH:
                pref = (IconListPreference) getContext()
                        .getListPreference(SettingConstants.ROW_SETTING_FLASH);
                break;
            default:
                break;
        }
        if (pref != null) {
            showOptionValues(pref, mButtonClicked, true);
        }
    }

    private boolean hideOptions() {
        boolean hide = false;
        if (isOptionsShowing()) {
            new AnimationFadeOut(mOptions).animate();
            new AnimationFadeIn(mPickerTop).animate();
            hide = true;
        }
        return hide;
    }

    private void onSceneClicked(final ListPreference pref) {
        mSceneApater = new SceneListAdapter(pref);
        mSceneList.setAdapter(mSceneApater);
        mSceneList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CharSequence value = pref.getEntryValues()[position];
                mListener.onScenePicked(value.toString());
                pref.setValueIndex(position);
                mHandler.postDelayed(mHideSceneList, DELAY_FOR_HIDE_SCENELIST);
            }
        });
        Util.setOrientation(mSceneListLayout, getOrientation(), false);
        mSceneListLayout.setVisibility(View.VISIBLE);
        mSceneApater.notifyDataSetChanged();
        startFadeInAnimation(mSceneListLayout);
        if (mListener != null) {
            mListener.onSceneListShowing(true);
        }
    }

    private boolean hideSceneList() {
        boolean hide = false;
        if (isSceneListShowing()) {
            startFadeOutAnimation(mSceneListLayout);
            mSceneListLayout.setVisibility(View.GONE);
            hide = true;
        }
        return hide;
    }

    private void startFadeInAnimation(View view) {
        if (mFadeIn == null) {
            mFadeIn = AnimationUtils.loadAnimation(getContext(), R.anim.setting_in);
        }
        if (view != null && mFadeIn != null) {
            view.startAnimation(mFadeIn);
        }
    }

    private void startFadeOutAnimation(View view) {
        if (mFadeOut == null) {
            mFadeOut = AnimationUtils.loadAnimation(getContext(), R.anim.setting_out);
        }
        if (view != null && mFadeOut != null) {
            mFadeOut.setAnimationListener(mSceneListFadeOutListener);
            view.startAnimation(mFadeOut);
        }
    }

    private class SceneListAdapter extends BaseAdapter {

        ListPreference mPref;

        public SceneListAdapter(ListPreference pref) {
            mPref = pref;
        }

        @Override
        public int getCount() {
            return mPref == null ? 0 : mPref.getEntries().length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (mPref == null) {
                return null;
            }
            convertView = inflate(R.layout.scene_list_item);
            TextView title = (TextView) (convertView.findViewById(R.id.title));
            ImageView icon = (ImageView) (convertView.findViewById(R.id.icon));
            icon.setImageResource(mPref.getIconId(position));
            title.setText(mPref.getEntries()[position]);
            if (mPref.getEntry().equals(mPref.getEntries()[position])) {
                icon.setSelected(true);
                title.setSelected(true);
            } else {
                icon.setSelected(false);
                title.setSelected(false);
            }
            return convertView;
        }
    }
}
